package com.doyens.filter;

import com.alibaba.fastjson.JSON;
import com.doyens.common.BaseContext;
import com.doyens.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //获取本次请求的URI
        String uri = request.getRequestURI();
        log.info("拦截到请求：{}",uri);

        //定义不需要处理的请求路径,存储在String类型的数组中
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //2.判断本次请求是否需要处理，自定义check方法判断
        boolean check = check(urls,uri);

        //3.如果不需要处理，则直接放行,调用filterChain.doFilter(req,resp)方法
        if(check){
            log.info("本次请求{}不需要处理",uri);
            filterChain.doFilter(request,response);
            //终止代码，不继续执行
            return;
        }

        //判断登录状态，如果已登录，则直接放行
//        if(request.getSession().getAttribute("employee") != null){
//            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
//            //获取当前登录客户端的用户id,存储进session域中
//            Integer userId = (Long) request.getSession().getAttribute("employee");
//            BaseContext.setCurrId(userId);
//            //2.执行放行
//            filterChain.doFilter(request,response);
//            return;
//        }

        //4.判断登录状态，若已登录，直接放行
        //通过获取session域的id值判断用户是否登录，不为空，代表已登录，放行
        if (request.getSession().getAttribute("employee") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
            Integer empId = (Integer) request.getSession().getAttribute("employee");
            //1.获取到当前登录用户的id值后，通过threadLocal类的set方法设置到threadLocal中
            BaseContext.setCurrId(empId);
            //2.执行放行
            filterChain.doFilter(request,response);
            return;
        }

        //5.用户未登录则显示未登录结果
        //根据前台页面接口提示返回json格式的字符串NOTLOGIN
        log.info("用户未登录...");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 定义check方法，判断本次请求是否可以放行
     * 通过路径匹配器判断本次请求是否需要放行
     * @param urls
     * @param uri
     * @return
     */
    private boolean check(String[] urls, String uri) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
